package com.ipan.poi.easyexcel.ehcache2;

import java.io.IOException;

import org.apache.poi.openxml4j.opc.PackagePart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.excel.cache.MapCache;
import com.alibaba.excel.cache.ReadCache;
import com.alibaba.excel.cache.selector.ReadCacheSelector;

/**
 * 支持EhCache2.x的版本
 * xlsx文件的共享字符串超过5M就使用ehcache，防止内存溢出；否则，全部加载到内存内；
 * 
 * @author iPan
 * @date 2022-01-21
 */
public class SimpleReadCacheSelector2 implements ReadCacheSelector {
	private static final Logger LOGGER = LoggerFactory.getLogger(SimpleReadCacheSelector2.class);
    /**
     * Convert bytes to megabytes
     */
    private static final long B2M = 1024 * 1024L;
    /**
     * If it's less than 5M, use map cache, or use ehcache.unit MB.
     */
    private static final int DEFAULT_MAX_USE_MAP_CACHE_SIZE = 5;
    /**
     * Maximum size of cache activation.unit MB.
     */
//    private static final int DEFAULT_MAX_EHCACHE_ACTIVATE_SIZE = 20;

    /**
     * 共享字符串的阈值，超过则使用ehcache，单位MB；
     */
    private long maxUseMapCacheSize;

    /**
     * 活动内存大小，单位MB；
     */
//    private int maxCacheActivateSize;

    public SimpleReadCacheSelector2() {
//        this(DEFAULT_MAX_USE_MAP_CACHE_SIZE, DEFAULT_MAX_EHCACHE_ACTIVATE_SIZE);
    	this(DEFAULT_MAX_USE_MAP_CACHE_SIZE);
    }

    public SimpleReadCacheSelector2(long maxUseMapCacheSize) {
        if (maxUseMapCacheSize <= 0) {
            this.maxUseMapCacheSize = DEFAULT_MAX_USE_MAP_CACHE_SIZE;
        } else {
            this.maxUseMapCacheSize = maxUseMapCacheSize;
        }
//        if (maxCacheActivateSize <= 0) {
//            this.maxCacheActivateSize = DEFAULT_MAX_EHCACHE_ACTIVATE_SIZE;
//        } else {
//            this.maxCacheActivateSize = maxCacheActivateSize;
//        }
    }

    @Override
    public ReadCache readCache(PackagePart sharedStringsTablePackagePart) {
        long size = sharedStringsTablePackagePart.getSize();
        if (size < 0) {
            try {
                size = sharedStringsTablePackagePart.getInputStream().available();
            } catch (IOException e) {
                LOGGER.warn("Unable to get file size, default used MapCache");
                return new MapCache();
            }
        }
        if (size < maxUseMapCacheSize * B2M) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Use map cache.size:{}", size);
            }
            return new MapCache();
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Use ehcache.size:{}", size);
        }
        return new EhCache2(); // 活动内存大小在配置文件XML内修改
    }
}
